<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemOAuth2ClientApi } from '#/api/system/oauth2/client';

import { defineProps, nextTick, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { createFileAppList, getFileAppList } from '#/api/infra/fileapp';
import { getFileCategoriesList } from '#/api/infra/filecategories';

import { useAssignFileCategoriesGridColumns } from '../data';

// 选择的应用
const props = defineProps({
  app: {
    type: Object as () => SystemOAuth2ClientApi.OAuth2Client,
    default: null,
  },
});

const isExpanded = ref(true); // 是否展开所有树节点

// 点击“展开/收起”按钮
function toggleExpand() {
  isExpanded.value = !isExpanded.value;
  if (gridApi?.grid) {
    gridApi.grid.setAllTreeExpand(isExpanded.value);
  }
}

// 保存授权
async function handleSave() {
  if (!props.app?.id) return;
  const hide = message.loading('正在保存权限...');
  try {
    // 只拿勾选的行
    const checkedRecords = gridApi.grid?.getCheckboxRecords() || [];

    // 半选的
    const halfCheckedRecords =
      gridApi.grid?.getCheckboxIndeterminateRecords() || [];

    // 合并一下
    const allSelected = [...checkedRecords, ...halfCheckedRecords];

    const payload = allSelected.map((r) => ({
      fileCategoriesId: r.id,
      code: r.code,
      readEnabled: r.readEnabled,
      writeEnabled: r.writeEnabled,
    }));

    await createFileAppList({
      appId: props.app.id,
      clientId: props.app.clientId,
      appName: props.app.name,
      fileAppSaveReqVOList: payload,
    });

    message.success('保存成功');
    await gridApi.reload();
  } catch {
    message.error('保存失败');
  } finally {
    hide();
  }
}

// vxe-grid
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    id: 'assign-filecategories-table',
    height: 'auto',
    columns: useAssignFileCategoriesGridColumns(),
    proxyConfig: {
      ajax: {
        query: async () => {
          return loadFileCategories(props.app);
        },
      },
    },
    pagerConfig: { enabled: false },
    rowConfig: { keyField: 'id', isHover: true },
    treeConfig: {
      transform: true,
      rowField: 'id',
      parentField: 'parentId',
      expandAll: true, // 默认展开所有节点
      accordion: false,
    },
    checkboxConfig: {
      highlight: true,
    },
    toolbarConfig: { refresh: true, search: true },
  } as VxeTableGridOptions,
});

// 监听 app 变化
watch(
  () => props.app,
  async (app) => {
    if (!app?.id) return;
    await nextTick();
    await gridApi.reload();
  },
  { immediate: true },
);

// 加载分类 & 授权
async function loadFileCategories(app: SystemOAuth2ClientApi.OAuth2Client) {
  if (!app?.id) return [];

  const hide = message.loading('加载文件分类...');
  try {
    const [allCategories, appAuths] = await Promise.all([
      getFileCategoriesList({}),
      getFileAppList({ appId: app.id }),
    ]);

    const authMap = new Map(appAuths.map((a) => [a.code, a]));

    const tableData = allCategories.map((c) => {
      const auth = authMap.get(c.code) || {};
      return {
        ...c,
        readEnabled: auth.readEnabled === true,
        writeEnabled: auth.writeEnabled === true,
      };
    });

    await nextTick();

    if (gridApi?.grid) {
      gridApi.grid.clearCheckboxRow(); // 先清空
      const rowsToCheck = tableData.filter((r) => authMap.has(r.code));
      gridApi.grid.setCheckboxRow(rowsToCheck, true); // 勾选新应用的授权
    }

    return tableData;
  } finally {
    hide();
  }
}
</script>

<template>
  <Grid table-title="文件分类列表">
    <template #toolbar-tools>
      <TableAction
        :actions="[
          {
            label: isExpanded ? '收缩' : '展开',
            type: 'dashed',
            onClick: toggleExpand,
          },
          { label: '保存', type: 'primary', onClick: handleSave },
        ]"
      />
    </template>
  </Grid>
</template>
